package com.bjpowernode.future;

import com.bjpowernode.util.ThreadUtils;

import java.util.concurrent.*;

/**
 * @ClassName MyCallable
 *
 * @Author Cat
 */
public class MyCallable implements Callable<String> {

    @Override
    public String call() throws Exception {
        System.out.println(Thread.currentThread().getName());
        ThreadUtils.sleep(3);
        return "OK";
    }

    public static void main(String[] args) throws Exception {
        /*//第一种方式：包装到FutureTask里面，然后通过Thread去运行Callable
        FutureTask<String> futureTask1 = new FutureTask<String>(new MyCallable());
        Thread t1 = new Thread(futureTask1);
        t1.start();

        //等待任务执行完毕，并返回结果
        String result = futureTask1.get();
        System.out.println("任务执行结果：" + result);

        FutureTask<String> futureTask2 = new FutureTask<String>(() -> {
            System.out.println(Thread.currentThread().getName());
            ThreadUtils.sleep(3);
            return "OK";
        });
        Thread t2 = new Thread(futureTask2);
        t2.start();
        String result2 = futureTask2.get();
        System.out.println("任务执行结果：" + result2);

        FutureTask<String> futureTask3 = new FutureTask<String>(new Callable<String>() {
            @Override
            public String call() throws Exception {
                System.out.println(Thread.currentThread().getName());
                ThreadUtils.sleep(3);
                return "OK";
            }
        });
        Thread t3 = new Thread(futureTask3);
        t3.start();
        String result3 = futureTask3.get();
        System.out.println("任务执行结果：" + result3);*/

        //第二种方式：使用“线程池”去运行Callable
        ExecutorService executorService = Executors.newSingleThreadExecutor();
        Future<String> future = executorService.submit(new MyCallable());
        //拿到执行结果
        System.out.println(future.get());

        executorService.shutdown();
    }
}